import { Context, Next } from 'koa'
import rolesService from '@/service/roles.service'
import { IRoleCreatParams, IRoleEditParams } from '@/types/roles.types'
import {
  ROLE_NAME_IS_REQUIRE,
  ROLE_ALREADY_EXISTS
} from '@/constants/error-types'

/**
 * 新增权限，参数检验
 * @param ctx
 * @param next
 * @returns
 */
const verifyAddRole = async (ctx: Context, next: Next): Promise<unknown> => {
  const { roleName, remark } = ctx.request.body as unknown as IRoleCreatParams
  // roleName&remark不能为空
  if (!roleName || !remark) {
    const error = new Error(ROLE_NAME_IS_REQUIRE)
    return ctx.app.emit('error', ctx, error)
  }

  // 判断roleName是否已经存在
  const res: any = await rolesService.getRoleByName({ roleName, remark })
  const roleRes = res[0]
  if (roleRes.length) {
    const error = new Error(ROLE_ALREADY_EXISTS)
    return ctx.app.emit('error', ctx, error)
  }

  await next()
}

const verifyEditRole = async(ctx: Context, next: Next) => {
  const { roleName, remark, id } = ctx.request.body as unknown as IRoleEditParams
  // roleName&remark不能为空
  if (!roleName || !remark || !String(id)) {
    const error = new Error(ROLE_NAME_IS_REQUIRE)
    return ctx.app.emit('error', ctx, error)
  }

  // 判断roleName是否已经存在
  const res: any = await rolesService.getOtherRoleByName({ id, roleName, remark })
  const roleRes = res[0]
  if (roleRes.length) {
    const error = new Error(ROLE_ALREADY_EXISTS)
    return ctx.app.emit('error', ctx, error)
  }

  await next ()
}

export {
  verifyAddRole,
  verifyEditRole
}